package dialog;

import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JSlider;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;

import model.Layer;
import utils.ImageOperationUtils;
import utils.ImageUtils;
import abstraction.ImageOperationDialog; 

/**
 * 
 * @author Maxime
 */
public class BrigthnessContrastFilterDialog extends ImageOperationDialog {

	public static final int DEFAULT_BRIGHTNESS = 0;
	public static final int DEFAULT_CONTRAST = 100;
	private JLabel m_brightnessLabel;
	private JLabel m_contrastLabel;
	private JSlider m_brightnessSlider;
	private JSlider m_contrastSlider;
	private JButton m_buttonBrightness;
	private JButton m_buttonContrast;
	private float brightnessValue = DEFAULT_BRIGHTNESS;
	private float contrastValue = DEFAULT_CONTRAST;

	public BrigthnessContrastFilterDialog(JFrame parent, Layer layer) {
		super(parent, layer.getImage());
		m_titleLabel.setText("Brightness / Contrast");
		m_componentPanel.setLayout(new GridLayout(2, 3));
		m_brightnessLabel = new JLabel("Brigtness : ");
		m_contrastLabel = new JLabel("Contrast : ");
		m_brightnessSlider = new JSlider(-255, 255, (int) brightnessValue);
		m_contrastSlider = new JSlider(0, 300, (int) contrastValue);
		m_buttonBrightness = new JButton("Reset");
		m_buttonContrast = new JButton("Reset");

		m_componentPanel.add(m_brightnessLabel);
		m_componentPanel.add(m_brightnessSlider);
		m_componentPanel.add(m_buttonBrightness);
		m_componentPanel.add(m_contrastLabel);
		m_componentPanel.add(m_contrastSlider);
		m_componentPanel.add(m_buttonContrast);

		m_contrastSlider.addChangeListener(new SliderListener());
		m_brightnessSlider.addChangeListener(new SliderListener());
		m_buttonBrightness.addActionListener(new ActionListener() {

			@Override
			public void actionPerformed(ActionEvent e) {
				brightnessValue = DEFAULT_BRIGHTNESS;
				m_brightnessSlider.setValue(DEFAULT_BRIGHTNESS);
			}
		});
		m_buttonContrast.addActionListener(new ActionListener() {

			@Override
			public void actionPerformed(ActionEvent e) {
				contrastValue = DEFAULT_CONTRAST;
				m_contrastSlider.setValue(DEFAULT_CONTRAST);
			}
		});

	}

	private class SliderListener implements ChangeListener {

		@Override
		public void stateChanged(ChangeEvent e) {

			JSlider slider = (JSlider) e.getSource();
			int value = slider.getValue();
			if (slider.equals(m_brightnessSlider)) {
				brightnessValue = value;
			} else if (slider.equals(m_contrastSlider)) {
				contrastValue = value;
			}
			m_preview = ImageOperationUtils.createRescaleOp(m_current, contrastValue, brightnessValue);
			m_imageLabel.setIcon(new ImageIcon(ImageUtils.resizeTo(m_preview,
					m_newWidth, m_newHeight)));
		}
	}
}
